import * as React from 'react';
import { Modal } from 'antd';
import Form from "react-jsonschema-form";
import { JSONSchema6 } from "json-schema";

interface Props {
    visible: boolean,
    schema: object,
    formData: any,
    submitInfo?: any
}

interface State extends Props {
    confirmLoading?: boolean
}

class Dialog extends React.Component<Props, {}> {
    public constructor(props: any) {
        super(props);
        this.state = {
            visible: this.props.visible,
            schema: this.props.schema,
            confirmLoading: false,
            formData: ''
        }
        this.handleCancel = this.handleCancel.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }


    public handleOk = () => {
        this.setState({
            confirmLoading: true,
        });
        setTimeout(() => {
            this.setState({
                visible: false,
                confirmLoading: false,
            });
        }, 2000);
    }

    public handleCancel = () => {
        this.setState({
            visible: false
        })
    }
    public componentWillReceiveProps = (nextProps: Props) => {
        if (nextProps.visible !== undefined) {
            this.setState({
                visible: nextProps.visible,
                formData: nextProps.formData
            })
        }
    }
    public onSubmit = (data: any) => {
        this.props.submitInfo(data);
    }

    public render() {
        const { visible, confirmLoading, schema, formData } = this.state as State;
        return (
            <div>
                <Modal
                    title="添加"
                    visible={visible}
                    onOk={this.handleOk}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleCancel}
                >
                    <Form schema={schema as JSONSchema6} onSubmit={this.props.submitInfo} formData={formData} />
                </Modal>
            </div>
        );
    }
}

export { Dialog, Props };